package com.ldn.basic.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import com.ldn.basic.utils.cache.HutoolCacheUtils;

/**
 * @author 李大牛家的牛 (scafel@163.com) 
 * @createDate 2024/9/12 - 14:34
 * @description ...
 **/
@Slf4j
@Component
public class LockUtil {


    // 根据code编码 获取一个Boolean如果有锁住就返回false 没有锁就返回true
    public synchronized static Boolean isLocked(String code) {
        assert code != null;
        String lock = HutoolCacheUtils.get(code);
        log.info("isLocked: " + lock + code);
        return !StrUtil.isBlank(lock);
    }

    public synchronized static void setLock(String code) {
        log.info("setLock: " + code);
        assert code != null;
        HutoolCacheUtils.set(code, "lock");
    }

    public static void unLock(String code) {
        log.info("unLock: " + code);
        assert code != null;
        HutoolCacheUtils.delKey(code);
    }

    public static boolean checkAndSetLock(String code) {
        long startTime = DateUtils.getCurrentS();
        boolean isTimedOut = false; // 添加一个标记变量来标识是否超时
        while (LockUtil.isLocked(code)) {
            // 超过5分钟后退出循环
            if (DateUtils.getCurrentS() - startTime > 60 * 5) {
                isTimedOut = true;
                break;
            }
            try {
                // 等待 1000 毫秒
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // 恢复中断状态
                Thread.currentThread().interrupt();
                // 记录日志或采取其他措施
                log.error("检查加锁时随眠报错-", e);
                break;
            }
        }
        if(isTimedOut){
            LockUtil.unLock(code);
        }else {
            LockUtil.setLock(code);
        }
        return isTimedOut;
    }

}
